<?php
namespace app\admin\controller;
use think\Controller;
use think\Request;
use think\Session;
use think\Cache;
use app\base\model\Admin;
class Login extends Controller {
    //管理员模型
    protected $admin;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->admin = new Admin();
    }
    public function login(){
        $user_name= $this->request->post('user_name');
        $password = $this->request->post('password');
        $userInfo=$this->admin->where(['user_login'=>$user_name])->find();
        if(empty($userInfo)){
            $msg['message']=checkMsg(USER_NOT_REG);
            return $msg;
        }
        if($userInfo['user_pass']!=md5($password)){
              $msg['message']=checkMsg(PASSWORD_ERROR);
              return $msg;
        }
        if($userInfo['user_status']==0){
           $msg['message']=checkMsg(USER_IS_FREEZE);
           return $msg;
        }
        $session_id=GetRandStr(50);
        Session::set($session_id,$userInfo,'admin');
        $this->admin->save(['last_login_time'=>time()],['user_login'=>$user_name]);
        $msg=checkMsg(LOGIN_SUCCESS);
        return ['message'=>$msg,'session_id'=>$session_id,'user_name'=>$user_name];
    }
    /**
     *退出登录
     * return json
     */
    public function logout(){
        $session_id  =$this->request->post('session_id');
        if(empty($session_id)){
            return $msg['message']=checkMsg(CANSHU_ERROR);
        }
        Session::delete($session_id,'admin');
        Cache::clear();
        $user_info=Session::get($session_id);
        if(empty($user_info)){
            $msg=checkMsg(LOGIN_OUT_SUCCESS);
        }else{
            $msg=checkMsg(LOGIN_OUT_FAIL);
        }
        return ['message'=>$msg];
    }
}